<template>
  <div class="evaluation-view">
    <!-- 头部导航 -->
    <div class="nav-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <div class="title">评价</div>
      <div class="placeholder"></div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 企业信息 -->
      <div class="company-info">
        <div class="company-name">上海上百杀虫科技有限公司</div>
      </div>

      <!-- 评价表单 -->
      <div class="form-content">
        <!-- 总体评价 -->
        <div class="form-item">
          <div class="form-label">总体</div>
          <div class="form-input">
            <van-rate
              v-model="formData.rating"
              :size="18"
              color="#ffd21e"
              void-color="#ebedf0"
              allow-half
              :gutter="2"
            />
          </div>
        </div>

        <!-- 文字描述 -->
        <div class="form-textarea-item">
          <div class="form-label">文字描述</div>
          <div class="textarea-container">
            <van-field
              v-model="formData.description"
              type="textarea"
              placeholder="防治效果如何，服务态度好吗（最多200字）"
              rows="4"
              maxlength="200"
              show-word-limit
              @input="updateWordCount"
            />
          </div>
        </div>

        <!-- 上传图片 -->
        <div class="form-upload-item">
          <div class="form-label">
            上传图片 <span class="upload-hint">（最多5张）</span>
          </div>
          <div class="upload-container">
            <van-uploader
              v-model="formData.images"
              multiple
              :max-count="5"
              :before-read="beforeRead"
              :after-read="afterRead"
              @delete="deleteImage"
              @click-preview="showImagePreview"
              :preview-full-image="false"
              :preview-options="{ showIndex: true }"
              :show-upload="formData.images.length < 5"
              accept="image/*"
              :image-fit="'cover'"
              :before-delete="() => true"
              class="custom-uploader"
            >
              <div class="upload-button">
                <van-icon name="photograph" size="20" />
              </div>
            </van-uploader>

            <div class="upload-guide" v-if="formData.images.length === 0">
              请上传相关图片
            </div>
          </div>
        </div>

        <!-- 上传视频 -->
        <div class="form-upload-item">
          <div class="form-label">
            上传视频 <span class="upload-hint">（大小限500MB内）</span>
          </div>
          <div class="upload-container">
            <!-- 如果已上传视频则显示视频播放器 -->
            <div
              v-if="formData.video.length > 0"
              class="video-container"
              @click="showVideoPlayer"
            >
              <video
                :src="formData.video[0].url"
                width="130px"
                height="74px"
                class="video-player"
              ></video>
              <div class="video-play-icon">
                <van-icon name="play-circle-o" size="24" />
              </div>
              <div class="video-delete" @click.stop="deleteVideo">
                <van-icon name="cross" size="16" />
              </div>
            </div>

            <!-- 如果没有上传视频则显示上传按钮 -->
            <van-uploader
              v-else
              v-model="formData.video"
              :after-read="afterVideoRead"
              accept="video/*"
              :max-count="1"
              @delete="deleteVideo"
            >
              <div class="video-upload-button">
                <van-icon name="video-o" size="20" />
              </div>
            </van-uploader>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部提交按钮 -->
    <div class="bottom-buttons">
      <van-button
        type="info"
        round
        class="submit-btn"
        @click="submitEvaluation"
      >
        完成提交
      </van-button>
    </div>

    <!-- 视频播放弹窗 -->
    <van-dialog
      v-model="showVideoDialog"
      title="视频播放"
      class="video-preview-dialog"
      :show-confirm-button="true"
      confirm-button-text="关闭"
      @confirm="closeVideoPlayer"
      @before-close="handleDialogBeforeClose"
    >
      <div class="video-dialog-content">
        <video
          v-if="formData.video.length > 0"
          :src="formData.video[0].url"
          controls
          autoplay
          class="dialog-video-player"
          ref="videoPlayerRef"
        ></video>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { Toast } from "vant";

export default {
  name: "EvaluationView",
  data() {
    return {
      // 表单数据
      formData: {
        rating: 4, // 默认4星
        description: "",
        images: [],
        video: [],
      },
      showVideoDialog: false,
      companyInfo: {
        name: "上海上百杀虫科技有限公司",
        id: "",
      },
    };
  },

  created() {
    this.loadEvaluationData();
  },

  methods: {
    goBack() {
      this.$router.go(-1);
    },

    // 加载评价相关数据
    async loadEvaluationData() {
      try {
        // 这里可以根据路由参数获取企业信息等
        const companyId = this.$route.params.companyId;
        console.log("加载评价数据:", companyId);
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    },

    // 更新字数统计
    updateWordCount() {
      // 字数统计逻辑
    },

    // 图片上传前处理
    beforeRead(file) {
      console.log("beforeRead", file);

      // 处理多选时，file是数组的情况
      if (Array.isArray(file)) {
        // 检查每个文件是否符合要求
        for (const item of file) {
          const isValid = this.checkFileType(item);
          if (!isValid) {
            return false; // 只要有一个文件不符合，就拒绝整个上传
          }
        }
        return true; // 所有文件都符合要求
      } else {
        // 单文件上传时，直接检查
        return this.checkFileType(file);
      }
    },

    // 检查文件类型的辅助函数
    checkFileType(file) {
      const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
      if (!allowedTypes.includes(file.type)) {
        Toast.fail("只能上传JPG、PNG或GIF图片");
        return false;
      }
      return true;
    },

    // 图片上传后处理
    afterRead(file) {
      // 处理多选的情况
      if (Array.isArray(file)) {
        // 如果是数组，对每个文件分别处理
        file.forEach((item) => {
          this.processUpload(item);
        });
        return true;
      } else {
        // 单文件上传
        return this.processUpload(file);
      }
    },

    // 处理单个文件的上传
    processUpload(file) {
      let fileObj, fileSize;

      // 判断文件格式
      if (file.file) {
        fileObj = file.file;
        fileSize = file.file.size;
      } else {
        fileObj = file;
        fileSize = file.size;
      }

      // 验证文件大小 (限制为5MB)
      if (fileSize > 5 * 1024 * 1024) {
        Toast.fail("图片大小不能超过5MB");
        return false;
      }

      // 保存初始URL，用于后续识别
      const initialUrl = file.content || file.url;
      console.log("初始图片URL:", initialUrl);

      // Vant会自动将此对象添加到v-model绑定的数组中
      file.status = "uploading";
      file.message = "上传中";

      console.log("开始上传:", file);

      // 调用模拟API
      this.simulateUploadApi(fileObj, () => {
        // 不显示进度百分比，只显示上传中状态
        file.status = "uploading";
        file.message = "上传中";

        // 强制更新视图
        this.formData.images = [...this.formData.images];
      })
        .then((res) => {
          console.log("上传成功", res);

          // 查找并更新图片对象
          const index = this.formData.images.findIndex(
            (item) =>
              (item.content && item.content === initialUrl) ||
              (item.url && item.url === initialUrl) ||
              item === file
          );

          if (index !== -1) {
            // 创建一个新的对象，保留原始属性但使用服务器URL
            const newFile = {
              ...file,
              url: res.data.url,
              content: undefined, // 清除content属性，以确保使用url属性
              status: "done",
              message: "",
              fileId: res.data.fileId,
            };

            // 替换数组中的对象
            this.formData.images.splice(index, 1, newFile);
            console.log("已完全替换图片对象", newFile);
          } else {
            console.error("未找到要更新的图片!");

            // 备用方案：仍然尝试更新当前对象
            file.url = res.data.url;
            file.content = undefined; // 清除content属性
            file.status = "done";
            file.message = "";
            file.fileId = res.data.fileId;
          }

          // 强制更新视图
          this.formData.images = [...this.formData.images];
          console.log("上传完成后的图片列表:", this.formData.images);

          // 提示上传成功
          Toast.success("图片上传成功");
        })
        .catch((err) => {
          console.error("上传失败", err);

          // 找到失败的图片在数组中的位置
          const index = this.formData.images.findIndex(
            (item) =>
              (item.content && item.content === initialUrl) ||
              (item.url && item.url === initialUrl) ||
              item === file
          );

          // 如果找到了该图片，从数组中移除
          if (index !== -1) {
            this.formData.images.splice(index, 1);
            console.log("已移除上传失败的图片");
          }

          // 强制更新视图
          this.formData.images = [...this.formData.images];
          console.log("上传失败后的图片列表:", this.formData.images);

          // 提示上传失败
          Toast.fail(`上传失败: ${err.message}`);
        });

      // 返回true表示组件应该保留此文件
      return true;
    },

    // 模拟文件上传API
    simulateUploadApi(file, onProgress) {
      return new Promise((resolve, reject) => {
        console.log("开始上传文件到服务器", file.name);

        // 模拟上传时间
        let progress = 0;
        const timer = setInterval(() => {
          progress += 10;
          if (onProgress) onProgress(progress);

          if (progress >= 100) {
            clearInterval(timer);

            // 模拟服务器返回数据
            setTimeout(() => {
              // 80%的概率上传成功
              if (Math.random() < 0.8) {
                // 使用固定外部URL作为服务器返回
                const serverUrl =
                  "https://ww2.sinaimg.cn/mw690/005EUiO2ly1hxj8yk8u5oj30m81c37d9.jpg";
                console.log("服务器返回的URL:", serverUrl);

                resolve({
                  code: 0,
                  message: "上传成功",
                  data: {
                    url: serverUrl,
                    fileId: "file_" + Date.now(),
                    fileName: file.name,
                    fileSize: file.size,
                    fileType: file.type,
                    status: "done",
                    message: "上传完成",
                  },
                });
              } else {
                // 模拟上传失败情况
                reject({
                  code: 500,
                  message: "服务器处理失败",
                });
              }
            }, 300);
          }
        }, 200);
      });
    },

    // 删除图片
    deleteImage(file, detail) {
      const index = detail.index;
      this.formData.images.splice(index, 1);
    },

    // 显示图片预览
    showImagePreview(item, detail) {
      const index = detail.index;
      const images = this.formData.images.map((item) => item.url);

      // 使用Vant的图片预览组件
      const imagePreview = Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });

      // 延迟一下关闭loading，显示预览
      setTimeout(() => {
        imagePreview.close();
        import("vant").then(({ ImagePreview }) => {
          ImagePreview({
            images,
            startPosition: index,
            closeable: true,
            closeIconPosition: "top-right",
          });
        });
      }, 300);
    },

    // 视频上传后处理
    afterVideoRead(file) {
      console.log("视频上传:", file);

      // 验证文件大小 (限制为500MB)
      if (file.file.size > 500 * 1024 * 1024) {
        Toast.fail("视频大小不能超过500MB");
        return;
      }

      // 验证文件类型
      const allowedTypes = ["video/mp4", "video/quicktime", "video/x-msvideo"];
      if (!allowedTypes.includes(file.file.type)) {
        Toast.fail("只支持主流视频格式");
        return;
      }

      // 创建视频对象
      const videoObj = {
        url: URL.createObjectURL(file.file),
        file: file.file,
        name: file.file.name,
        isVideo: true,
      };

      // 清空现有视频并添加新视频
      this.formData.video = [videoObj];
      console.log("formData.video", this.formData.video);
    },

    // 删除视频
    deleteVideo() {
      this.formData.video = [];
    },

    // 显示视频播放器
    showVideoPlayer() {
      this.showVideoDialog = true;
    },

    // 关闭视频播放器
    closeVideoPlayer() {
      this.showVideoDialog = false;
    },

    // 对话框关闭前处理
    handleDialogBeforeClose() {
      if (this.$refs.videoPlayerRef) {
        this.$refs.videoPlayerRef.pause();
      }
      return true;
    },

    // 提交评价
    async submitEvaluation() {
      console.log("提交评价", this.formData);
      try {
        // 验证表单
        if (this.formData.rating === 0) {
          Toast.fail("请选择评价星级");
          return;
        }

        if (!this.formData.description.trim()) {
          Toast.fail("请填写文字描述");
          return;
        }

        // 提交数据
        const evaluationData = {
          companyId: this.companyInfo.id,
          rating: this.formData.rating,
          description: this.formData.description,
          images: this.formData.images,
          video: this.formData.video,
        };

        console.log("提交评价数据:", evaluationData);

        // 调用API提交评价
        // const response = await this.$api.evaluation.submit(evaluationData);
        // if (response.success) {
        //   Toast.success("评价提交成功");
        //   this.$router.go(-1);
        // }

        Toast.success("评价提交成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 1500);
      } catch (error) {
        console.error("提交评价失败:", error);
        Toast.fail("提交失败，请重试");
      }
    },
  },
};
</script>

<style scoped>
.evaluation-view {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 头部导航样式 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 46px;
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
  padding: 0 16px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-icon {
  font-size: 20px;
  color: #323233;
  cursor: pointer;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.placeholder {
  width: 20px;
}

/* 内容区域 */
.content {
  padding: 0;
  background-color: #f5f5f5;
  min-height: calc(100vh - 46px);
  padding-bottom: calc(80px + 16px);
}

/* 企业信息 */
.company-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 16px;
  margin: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.company-name {
  font-size: 15px;
  font-weight: 500;
  color: #323233;
  line-height: 21px;
}

/* 表单内容 */
.form-content {
  padding: 0 16px 0 16px;
  border-radius: 4px;
  background-color: #fff;
  margin: 8px 16px;
}

.form-item {
  display: flex;
  align-items: center;
  background-color: transparent;
  padding: 0;
  border-bottom: 1px solid #ebedf0;
  min-height: 50px;
  margin-bottom: 0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-textarea-item {
  background-color: transparent;
  padding: 12px 0;
  border-bottom: 1px solid #ebedf0;
  margin-bottom: 0;
}

.form-upload-item {
  background-color: transparent;
  padding: 12px 0;
  border-bottom: 1px solid #ebedf0;
  margin-bottom: 0;
}

.form-label {
  height: 20px;
  font-family:
    PingFangSC,
    PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #666666;
  line-height: 20px;
  min-width: 80px;
}

.form-input {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-height: 20px;
}

.upload-hint {
  font-size: 12px;
  color: #969799;
}

.textarea-container {
  margin-top: 12px;
}

.upload-container {
  margin-top: 12px;
  width: 100%;
}

.upload-button {
  width: 98px;
  height: 74px;
  min-height: 74px;
  background: #f7f8fa;
  border: 1px dashed #c8c9cc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c8c9cc;
  box-sizing: border-box;
  flex-shrink: 0;
  margin-bottom: 8px;
}

.upload-button:nth-child(3n) {
  margin-right: 0;
}

.video-upload-button {
  width: 130px;
  height: 74px;
  background: #f7f8fa;
  border: 1px dashed #c8c9cc;
  border-image: none;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c8c9cc;
  box-sizing: border-box;
  position: relative;
}

.upload-guide {
  font-size: 12px;
  color: #969799;
  margin-top: 8px;
  line-height: 1.4;
}

/* 视频容器样式 */
.video-container {
  position: relative;
  width: 130px;
  height: 74px;
  margin-bottom: 10px;
  border-radius: 4px;
}

.video-player {
  width: 100%;
  height: 100%;
  background: #000;
  display: block;
  border-radius: 4px;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.video-play-icon:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.video-play-icon .van-icon {
  font-size: 24px;
  color: #fff;
}

.video-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ee0a24;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
}

.video-delete .van-icon {
  font-size: 12px;
  color: #fff;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 16px;
  padding-bottom: calc(16px + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  flex: 1;
  background-color: #1989fa;
  border-color: #1989fa;
}

/* 修改Vant样式 */
:deep(.van-field__control) {
  text-align: left;
  height: auto;
  font-family:
    PingFangSC,
    PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #333333;
  line-height: 20px;
}

:deep(.form-textarea-item .van-field) {
  background: transparent;
  padding: 0;
}

:deep(.form-textarea-item .van-field__control) {
  text-align: left;
  padding: 0;
}

:deep(.van-field__word-limit) {
  text-align: right;
  margin-top: 4px;
  color: #969799;
}

:deep(.van-field) {
  background: transparent;
}

/* 自定义上传组件样式 */
:deep(.van-uploader) {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  width: 100%;
}

:deep(.van-uploader__upload) {
  background: transparent !important;
  border: none !important;
  width: 98px !important;
  height: 74px !important;
  min-height: 74px !important;
  margin: 0 10px 8px 0 !important;
  flex-shrink: 0 !important;
}

:deep(.van-uploader__upload:nth-child(3n)) {
  margin-right: 0 !important;
}

:deep(.van-uploader__preview) {
  margin: 0 8px 8px 0 !important;
  width: 98px !important;
  height: 74px !important;
}

:deep(.van-uploader__preview:nth-child(3n)) {
  margin-right: 0 !important;
}

:deep(.van-uploader__preview-image) {
  border-radius: 4px;
  overflow: hidden;
  width: 100% !important;
  height: 100% !important;
  object-fit: cover;
}

/* 星级评价样式 */
:deep(.van-rate) {
  display: flex;
  align-items: center;
}

:deep(.van-rate__item) {
  margin-right: 2px;
}

:deep(.van-rate__item:last-child) {
  margin-right: 0;
}

:deep(.van-rate__icon) {
  font-size: 18px;
}

/* 视频预览对话框样式 */
:deep(.video-preview-dialog) {
  width: 90% !important;
  max-width: 600px;
}

:deep(.video-preview-dialog .van-dialog__content) {
  padding: 0;
}

:deep(.video-preview-dialog .van-dialog__message) {
  padding: 0;
}

.video-dialog-content {
  padding: 0;
}

.dialog-video-player {
  width: 100%;
  max-height: 70vh;
  display: block;
  background: #000;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .content {
    padding: 0;
    padding-bottom: calc(80px + 14px);
  }

  .company-info {
    padding: 14px;
    margin: 10px 16px;
  }

  .company-name {
    font-size: 15px;
  }

  .form-content {
    padding: 0 14px;
  }

  .form-item {
    min-height: 40px;
  }

  .form-label {
    min-width: 70px;
    font-size: 13px;
  }

  .upload-button {
    width: 88px;
    height: 66px;
    min-height: 66px;
  }

  .video-upload-button {
    width: 120px;
    height: 66px;
  }

  .bottom-buttons {
    padding: 14px;
    padding-bottom: calc(14px + env(safe-area-inset-bottom));
  }
}

@media (min-width: 376px) and (max-width: 768px) {
  .content {
    padding: 0;
    padding-bottom: calc(80px + 16px);
  }

  .company-info {
    margin: 16px 16px;
  }
}
</style>
